package com.ly.hotel.spainterface.jg.view;

import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.spainterface.jg.adapter.MassageHideAdapter;
import com.ly.hotel.spainterface.jg.adapter.MassageOperateInfoAdapter;
import com.ly.hotel.spainterface.jg.bean.Massage;
import com.ly.hotel.spainterface.jg.bean.MassageBean;
import com.ly.hotel.spainterface.jg.bean.MassageItem;
import com.ly.hotel.spainterface.jg.bean.gson.dbfile.DbRead;
import com.ly.hotel.spainterface.jg.bean.gson.dbfile.DbWrite;
import com.ly.hotel.spainterface.jg.bean.gson.goods.Goods;
import com.ly.hotel.spainterface.jg.bean.gson.goods.GoodsResult;
import com.ly.hotel.spainterface.jg.bean.gson.postJson.GoodsPara;
import com.ly.hotel.spainterface.jg.utils.GsonUtils;
import com.ly.hotel.spainterface.jg.utils.OkHttpUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by ThinkPad on 2018/3/1.
 */

public class CustomGoodsShowDialog extends DialogFragment {

    private String serverIP;
    private String serverPORT;
    private String cashierIp;
    private String cashierPort;
    private int[] judgeNum = {0,1,2};// 0：提交隐藏的商品编码，1：请求小类数据，2：获得隐藏的商品编码文本
    private String[] goodsHideNo;// 隐藏的商品编号数组
    private Map<String,Boolean> map = new HashMap<>();
    private View view;
    private List<MassageItem> massageItemList;
    private int massagePosition;
    private ListView goodsShowListView;
    private LinearLayout noGoodsInfoTips;
    private CustomLoadingDialog loadingDialog;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    String jsonString = msg.obj.toString();
                    Log.d("GoodsShowDialog",jsonString);
                    if(msg.arg1 == judgeNum[1]) {
                        loadingDialog.close();
                        GoodsResult goodsResult = GsonUtils.parseSimpleJson(jsonString, GoodsResult.class);
                        if(goodsResult.isSuccess()){
                            List<Goods> goodses = goodsResult.getResult().getLstGoods();
                            massageItemList = new ArrayList<>();
                            for(int i = 0;i < goodses.size();i ++){
                                Goods goods = goodses.get(i);
                                MassageItem massageItem = new MassageItem();
                                massageItem.setId(goods.getGoodsId());
                                massageItem.setName(goods.getGoodsName());
                                massageItem.setUnit(goods.getUnit());
                                massageItem.setPrice(Double.parseDouble(goods.getPrice()));
                                if(goodsHideNo != null){
                                    for(int j = 0;j < goodsHideNo.length;j ++){
                                        if(massageItem.getId().equals(goodsHideNo[j])){
                                            massageItemList.add(massageItem);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        Log.d("GoodsShowDialog","被隐藏的商品数量：" + massageItemList.size());
                        if(massageItemList.size() == 0){
                            ListView goodsInfo = view.findViewById(R.id.goods_info);
                            goodsInfo.setVisibility(View.GONE);
                            noGoodsInfoTips.setVisibility(View.VISIBLE);
                        }else{
                            setMassageItemInfo();
                        }
                    }else if(msg.arg1 == judgeNum[2]){
                        DbRead dbRead = GsonUtils.parseSimpleJson(jsonString,DbRead.class);
                        if(dbRead.getCode() == 200){
                            String data = dbRead.getData();
                            Log.d("GoodsShowDialog","隐藏商品编号：" + data);
                            if(! TextUtils.isEmpty(data)){
                                goodsHideNo = data.split(" ");
                            }
                        }else{
                            goodsHideNo = null;
                        }
                    }else if(msg.arg1 == judgeNum[0]){
                        DbWrite dbWrite = GsonUtils.parseSimpleJson(jsonString, DbWrite.class);
                        if(dbWrite.getCode() == 200){
                            // 请求隐藏的商品数据
                            getGoodsHide();
                            // 模拟点击了商品大类(提交成功后)
                            goodsShowListView.performItemClick(goodsShowListView.getChildAt(0),massagePosition, goodsShowListView.getItemIdAtPosition(0));

                            Toast.makeText(MyApplication.getContext(),"显示提交成功",Toast.LENGTH_SHORT).show();

                        }else{
                            Toast.makeText(MyApplication.getContext(),"显示提交失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;

                case 2:
                    if(loadingDialog != null){
                        loadingDialog.close();
                    }
                    if(msg.arg2 == judgeNum[0]){

                    }else if(msg.arg2 == judgeNum[2]){
                        ListView goodsInfo = (ListView) view.findViewById(R.id.goods_info);
                        LinearLayout noGoodsInfoTips = (LinearLayout) view.findViewById(R.id.no_goods_info_tips);
                        goodsInfo.setVisibility(View.GONE);
                        noGoodsInfoTips.setVisibility(View.VISIBLE);
                        Toast.makeText(MyApplication.getContext(),"无法获取隐藏商品数据",Toast.LENGTH_SHORT).show();
                    }else if(msg.arg2 == judgeNum[1]){

                    }
                    break;
            }
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.widthPixels * 0.5), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.windowAnimations = R.style.customDialogAnim;
        window.setAttributes(layoutParams);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

        Bundle bundle = getArguments();
        MassageBean massageBean = (MassageBean) bundle.getSerializable("massageBean");
        final List<Massage> massageList = massageBean.getMassageList();
        serverIP = bundle.getString("serverIP","");
        serverPORT = bundle.getString("serverPORT","");
        cashierIp = bundle.getString("cashierIP","");
        cashierPort = bundle.getString("cashierPORT","");

        view = inflater.inflate(R.layout.jg_goods_show_layout,container,false);
        ImageButton goodsShowClose = view.findViewById(R.id.goods_show_close);
        goodsShowListView = view.findViewById(R.id.goods_show_listview);
        goodsShowListView.setVerticalScrollBarEnabled(false);
        noGoodsInfoTips = view.findViewById(R.id.no_goods_info_tips);

        //final MassageAdapter massageAdapter = new MassageAdapter(MyApplication.getContext(),massageList,true);
        final MassageHideAdapter massageAdapter = new MassageHideAdapter(MyApplication.getContext(),massageList);
        goodsShowListView.setAdapter(massageAdapter);
        goodsShowListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                massageAdapter.setDefaultItem(position);
                Massage massage = massageList.get(position);
                String massageId = massage.getId();
                massagePosition = position;
                loadingDialog = new CustomLoadingDialog(getActivity(),"加载中...");
                loadingDialog.show();
                getGoods(massageId);
            }
        });
        goodsShowListView.performItemClick(goodsShowListView.getChildAt(0),0, goodsShowListView.getItemIdAtPosition(0));

        goodsShowClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        // 获取隐藏的商品数据
        getGoodsHide();
        return view;
    }

    // 请求消费小类的数据
    private void getGoods(String CatalogId){
        Map<String,String> map = new HashMap<>();
        map.put("CatalogId",CatalogId);
        GoodsPara goodsPara = new GoodsPara();
        goodsPara.setCatalogId(CatalogId);
        Gson gson = new Gson();
        String jsonString = gson.toJson(goodsPara);// 提交的json数据
        String url = "http://" + cashierIp + ":" + cashierPort + "/TsInterface/Ts_GetGoods";
        OkHttpUtils.getInstance().postJsonResource(jsonString,url,handler,judgeNum[1]);
    }

    // 获得隐藏的商品文本
    public void getGoodsHide(){
        String url = "http://" + serverIP + ":" + serverPORT + "/api/dbfile-read.json?filename=JGGoodsHide&content=";
        OkHttpUtils.getInstance().getTextResource(url,handler,judgeNum[2]);
    }

    // 处理隐藏商品的小类信息
    public void setMassageItemInfo(){
        ListView goodsInfoListView = (ListView) view.findViewById(R.id.goods_info);
        goodsInfoListView.setVisibility(View.VISIBLE);
        noGoodsInfoTips.setVisibility(View.GONE);
        goodsInfoListView.setVerticalScrollBarEnabled(false);
        MassageOperateInfoAdapter adapter = new MassageOperateInfoAdapter(MyApplication.getContext(),massageItemList);
        goodsInfoListView.setAdapter(adapter);
        goodsInfoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckBox goodsShowOperate = (CheckBox) view.findViewById(R.id.goods_hide_operate);
                if(goodsShowOperate.isChecked()){
                    goodsShowOperate.setChecked(false);
                }else{
                    goodsShowOperate.setChecked(true);
                }
            }
        });
        map = adapter.getMap();
        submitGoodsHide();
    }

    // 提交隐藏的商品
    public void submitGoodsHide(){
        TextView goodsShowSubmit = (TextView) view.findViewById(R.id.goods_show_submit);
        goodsShowSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> goodsHideNoList = new ArrayList<>();
                if(goodsHideNo != null){
                    for(int i = 0;i < goodsHideNo.length;i ++){
                        goodsHideNoList.add(goodsHideNo[i]);
                    }
                }

                if(map != null && map.size() > 0 && goodsHideNoList.size() > 0){
                    Iterator<Map.Entry<String,Boolean>> it = map.entrySet().iterator();
                    while (it.hasNext()){
                        Map.Entry<String,Boolean> entry = it.next();
                        for(int j = 0;j < goodsHideNoList.size();j ++){
                            if(goodsHideNoList.get(j).equals(entry.getKey())){
                                goodsHideNoList.remove(j);
                            }
                        }
                    }

                    String content = "";
                    for(int i = 0;i < goodsHideNoList.size();i ++){
                        content += goodsHideNoList.get(i) + " ";
                    }
                    Log.d("GoodsShowDialog","content=" + content);

                    String url = "http://" + serverIP + ":" + serverPORT + "/api/dbfile-write.json?filename=JGGoodsHide&content=" + content + "&isappend=false";
                    OkHttpUtils.getInstance().getTextResource(url,handler,judgeNum[0]);

                    map = null;
                }else {
                    Toast.makeText(MyApplication.getContext(),"请选择需要显示的商品",Toast.LENGTH_SHORT).show();
                }

            }
        });

    }
}
